<?php 
/*
 module:		Mbti订单表
 create_time:	2024-04-22 17:31:27
 author:		
 contact:		
*/

namespace app\api\service\Mbti;
use app\api\model\Mbti\Order;
use think\facade\Log;
use think\exception\ValidateException;
use utils\weixinpay\wechatpay;
use xhadmin\CommonService;
/**start**/
use think\facade\Db;
/**end**/
class OrderService extends CommonService {





 /**start**/
	/*
 	* @Description  创建数据
 	*/
	public static function save($data,$uid){
		try{
            $id = $data['mbti_id'];
            if(!is_numeric($id)){
                throw new ValidateException("没有找到资源");
            }
            $arr = Db::name('mbti')
                ->where('extension',1)
                ->where("mbti_id",$id)
                ->count();
            if($arr === 0){
                throw new ValidateException("没有找到资源");
            }
            $mbti = Db::name('mbti')->where('mbti_id',$id)->find();

            $price = Db::name("mbti_price")->where("mbti_id",$id)->value("price");

            $arr = [];
            $order =doOrderSn('DSS');
            $arr["uid"] = $uid;
            $arr['order_son'] = $order;
            $arr['title'] = $mbti['title'];
            $arr['price'] = $price;
            $arr['money'] = $mbti['money'];
            $arr['mbti_id'] = $id;
            $arr['create_time'] = time();
			$res = Order::create($arr);
		}catch(ValidateException $e){
			throw new ValidateException ($e->getError());
		}catch(\Exception $e){
			abort(config('my.error_log_code'),$e->getMessage());
		}
		return ['order_son'=>$order];
	}

    public static function getTopic($data){
        try{
            $order_son = $data['order_son'];
            $arr = Db::name('order')
                ->where('order_son',$order_son)
                ->count();
            if($arr === 0){
                throw new ValidateException("未知错误");
            }
            $order = Db::name('order')->where('order_son',$order_son)->find();
            $mbti_id = $order['mbti_id'];
            //结果


            //题目
            $mbti_subject = Db::name('mbti_subject')
                ->alias('ms')
                ->join("mbti_option mo",'ms.subject_id = mo.subject_id',"right")
                ->where('ms.mbti_id',$mbti_id)
                ->where("ms.type","1")
                ->order("ms.sort asc")
                ->field("ms.mt_id,ms.subject_id,ms.mbti_id,ms.option_type,ms.title,mo.option_title,mo.mo_id,mo.fraction,mo.fraction2")
                ->select()->toArray();

            //题目类型
            $mbti_topictype = Db::name("mbti_topictype")
                ->where("mbti_id",$mbti_id)
                ->field("type_name")
                ->order("sort","asc")
                ->column("type_name","mt_id");
            $array = [];
            $key_val = [];
            $j = 0;
            foreach ($mbti_topictype as $k=>$v){
                $array[$j]["type_name"] = $v;
                $array[$j]["count"] = 0;
                $array[$j]["select_count"] = 0;
                $key_val[$k] = $j;
                $j++;
            }
            $arr = [];
            $i = 0;
            foreach ($mbti_subject as $k=>$v){
                if(!isset($array[$key_val[$v['mt_id']]]["list"][$v['subject_id']])){
                    $array[$key_val[$v['mt_id']]]['count'] += 1;
                    $arr[$i]['question_list'][]=['mo_id'=>$v['mo_id'],'content'=>$v['option_title']];

                }else{
                    $arr[$i]['title'] = $v['title'];
                    $arr[$i]['sub_id'] = $v['subject_id'];
                    $arr[$i]['option_type'] = $v['option_type'];
                    $arr[$i]['question_list'][] = ['mo_id'=>$v['mo_id'],'content'=>$v['option_title']];
                    $arr[$i]['user_option_choice'] = '';
                   $i++;
                    $array[$key_val[$v['mt_id']]]["list"][$v['subject_id']]['option_type'] = $v['option_type'];
                    $array[$key_val[$v['mt_id']]]["list"][$v['subject_id']]['user_option_choice'] = "";
                    $array[$key_val[$v['mt_id']]]["list"][$v['subject_id']]['user_option_id'] = "";
                }
                $array[$key_val[$v['mt_id']]]["list"][$v['subject_id']]['title'] = $v['title'];
                $array[$key_val[$v['mt_id']]]["list"][$v['subject_id']]['sub_id'] = $v['subject_id'];


                $array[$key_val[$v['mt_id']]]["list"][$v['subject_id']]["question_list"][$v['mo_id']]["content"] = $v['option_title'];
                $array[$key_val[$v['mt_id']]]["list"][$v['subject_id']]["question_list"][$v['mo_id']]["mo_id"] = $v['mo_id'];
            }
            $topic = [];
            //数组合并
            foreach ($array as $v){
                $topic = array_merge($topic,$v['list']);
            }
            if(empty($mbti_subject)){
                throw new ValidateException("请检查是否正确啊");
            }

        }catch(ValidateException $e){
            throw new ValidateException ($e->getError());
        }catch(\Exception $e){
            abort(config('my.error_log_code'),$e->getMessage());
        }
        return ['list'=>$array,'topic'=>$topic];
    }
    /**
     * 算出题目
     */
    public static function subResult($data){
        try{
            $order_son = $data['order_son'];
            $list = $data['data'];
            $second = $data["second"]?$data["second"]:0;
            $arr = Db::name('order')
                ->where('order_son',$order_son)
                ->count();
            if($arr === 0){
                throw new ValidateException("未知错误");
            }
            $order = Db::name('order')->where('order_son',$order_son)->find();
            $mbti_id = $order['mbti_id'];
            //结果


            //题目
            $mbti_subject = Db::name('mbti_subject')
                ->alias('ms')
                ->join("mbti_option mo",'ms.subject_id = mo.subject_id',"right")
                ->where('ms.mbti_id',$mbti_id)
                ->where("ms.type","1")
                ->order("ms.sort asc")
                ->field("mo.option_title,mo.mo_id,mo.fraction,mo.fraction2,factor")
                ->select()->toArray();
//            var_dump($mbti_subject);
            $wo_list = array_column($mbti_subject,null,'mo_id');
            $array =[];
            $yz = ["T" => 0,
                "N" => 0,
                "E" => 0,
                "J" =>0,
                "F" =>0,
                "S" => 0,
                "I" =>0,
                "P" => 0];
            foreach ($list as $k=>$v){
                $arr = [];
                if($v['option_type']==1){
                    //多选
                    if($v['user_option_choice'] == 0 || $v['user_option_choice'] == 1){
                        $index = 0;
                        if(isset($wo_list[$v['question_list'][$index]['mo_id']])){
                            $jg=$wo_list[$v['question_list'][$index]['mo_id']]['factor'];
                        }else{
                            throw new ValidateException("未知错误");
                        }

                        $yz[$jg] +=1;
                        $zjg= $jg;
                    }else if($v['user_option_choice'] == 3 || $v['user_option_choice'] == 4){
                        $index = 1;
                        if(isset($wo_list[$v['question_list'][$index]['mo_id']])){
                            $jg=$wo_list[$v['question_list'][$index]['mo_id']]['factor'];
                        }else{
                            throw new ValidateException("未知错误");
                        }
                        $yz[$jg] +=1;
                        $zjg= $jg;
                    }else{
                        //两个都加1
                        $index = 0;
                        if(isset($wo_list[$v['question_list'][$index]['mo_id']])){
                            $jg1=$wo_list[$v['question_list'][$index]['mo_id']]['factor'];
                        }else{
                            throw new ValidateException("未知错误");
                        }
                        $yz[$jg1] +=1;
                        $index = 1;
                        if(isset($wo_list[$v['question_list'][$index]['mo_id']])){
                            $jg2=$wo_list[$v['question_list'][$index]['mo_id']]['factor'];
                        }else{
                            throw new ValidateException("未知错误");
                        }
                        $yz[$jg2] +=1;
                        $zjg= $jg1.','.$jg2;
                    }
                    $arr['id'] = $v['sub_id'];
                    $arr['jg'] = $zjg;
                }else{
                    //单选
                    $index = $v['user_option_choice'];
                    if(isset($wo_list[$index])){
                         $jg=$wo_list[$index]['factor'];
                    }else{
                        throw new ValidateException("未知错误");
                    }
                    $yz[$jg] +=1;
                    $arr['id'] = $v['sub_id'];
                    $arr['jg'] = $jg;
                }
                $array[] = $arr;
            }
            //用户选择的结果
            $json = json_encode($array);
            $fraction_json = json_encode($yz);
            $zzjg= self::results($yz);
            $zzjgJson = json_encode($zzjg);
            //最终结果
            Db::name("order")->where("order_son",$order_son)->update(["outcome"=>$zzjg[0],"select_out"=>$json,"fraction_json"=>$fraction_json,"outcome_json"=>$zzjgJson,"update_time"=>time()]);
            //查找一下上级的订单id
            if($second != ""){
                $s_order = Db::name("order")->where("order_id",$second)->find();
                //状态要是0才行
                if($s_order["state"] == 0){

                    $time = $s_order["update_time"] + 86400;
                    $remain_time = $time - time();
                    if($remain_time > 0){
                        //不能是自己
                        if(!empty($s_order) && $s_order["uid"] != $order["uid"]){

                            //查找该用户是否已经解锁一次了
                            $sec = Db::name("order_share")->where("uid",$order["uid"])->count();
                            if(!$sec){
                                Db::name("order_share")->insert([
                                    "uid"=>$order["uid"],
                                    "oid"=>$second,
                                    "pid"=>$s_order["uid"],
                                    "order_id"=>$order["order_id"],
                                ]);
                                //顺便查一下是否达到了解锁
                                $count = Db::name("order_share")->where("oid",$second)->count();
                                //大于3个就解锁了上级的订单
                                if($count >= 3){
                                    Db::name("order")->where("order_id",$second)->update(["state"=>1,"type"=>"2"]);
                                }
                            }
                        }
                    }
                }


            }




        }catch(ValidateException $e){
            throw new ValidateException ($e->getError());
        }catch(\Exception $e){
            abort(config('my.error_log_code'),$e->getMessage());
        }
        return ['order_son'=>$order_son,"state"=>$order['state']];
    }
    public static function results($arr){

        $res = [];
        $ei = $arr['E'] + $arr['I'];
        if($arr['E'] == $arr['I']){
            $res[0]['di']= bcdiv($arr['I'],$ei,4) * 100;
            $res[0]['re']='I';
        }else if($arr['E'] < $arr['I']){
            $res[0]['di']=  bcdiv($arr['I'],$ei,4) * 100;
            $res[0]['re']= 'I';
        }else if($arr['E'] > $arr['I']){
            $res[0]['di']= bcdiv($arr['E'],$ei,4) * 100;
            $res[0]['re']= 'E';
        }

        $sn = $arr['S'] + $arr['N'];
        if($arr['S'] == $arr['N']){
            $res[1]['di']= bcdiv($arr['N'],$sn,4) * 100;
            $res[1]['re']= 'N';
        }else if($arr['S'] < $arr['N']){
            $res[1]['di']= bcdiv($arr['N'],$sn,4) * 100;
            $res[1]['re']= 'N';
        }else if($arr['S'] > $arr['N']){
            $res[1]['di']= bcdiv($arr['S'],$sn,4) * 100;
            $res[1]['re']= 'S';
        }
        $tf = $arr['T'] + $arr['F'];
        if($arr['T'] == $arr['F']){
            $res[2]['di']= bcdiv($arr['F'],$tf,4) * 100;
            $res[2]['re']= 'F';
        }else if($arr['T'] < $arr['F']){
            $res[2]['di']= bcdiv($arr['F'],$tf,4) * 100;
            $res[2]['re']= 'F';
        }else if($arr['T'] > $arr['F']){
            $res[2]['di']= bcdiv($arr['T'],$tf,4) * 100;
            $res[2]['re']= 'T';
        }
        $jp = $arr['J'] + $arr['P'];
        if($arr['J'] == $arr['P']){
            $res[3]['di']= bcdiv($arr['P'],$jp,4) * 100;
            $res[3]['re']= 'P';
        }else if($arr['J'] < $arr['P']){
            $res[3]['di']= bcdiv($arr['P'],$jp,4) * 100;
            $res[3]['re']= 'P';
        }else if($arr['J'] > $arr['P']){
            $res[3]['di']= bcdiv($arr['J'],$jp,4) * 100;
            $res[3]['re']= 'J';
        }
        $data = [];
        $data[] = $res[0]['re'].$res[1]['re'].$res[2]['re'].$res[3]['re'];
        $data[] = $res;
        return $data;
    }

    /**
     * 返回成功结果
     */
    public static function result_answer($data)
    {
        try{
            $order_son = $data['order_son'];
            $list = $data['data'];
            $arr = Db::name('order')
                ->where('order_son',$order_son)
                ->count();
            if($arr === 0){
                throw new ValidateException("未知错误");
            }
            $order = Db::name('order')->where('order_son',$order_son)->find();
            $mbti_id = $order['mbti_id'];
            $outcome = json_decode($order['outcome_json'],true);
            $outcome_str = '';
            foreach ($outcome[1] as $v){
                $outcome_str .= $v['re'].',';
            }
            $outcome_str = rtrim($outcome_str,',');
            $list = Db::name("mbti_result")
                ->alias('mr')
                ->join("mbti_complete mc","mc.result_id = mr.result_id")
                ->where(["results"=>$outcome_str,"mbti_id"=>$mbti_id])
                ->field("mc.title,mc.content")
                ->select()
                ->toArray();

            $results = $order['outcome'];
            $fraction =  json_decode($order['fraction_json'],true);
            $factor_name = Db::name("mbti_factor")->where("mbti_id",$mbti_id)->column("factor_name","factor_iden");
            $factor_array = [];
            foreach ($factor_name as $k=>$v){
                $factor_array[]=["name"=>$v,"score"=>$fraction[$k],"frac"=>$k];
            }
//            foreach ($list  as $k=>$v){
//                $list[$k]["content"] = html_entity_decode($v['content']);
//            }
            //结果

        }catch(ValidateException $e){
            throw new ValidateException ($e->getError());
        }catch(\Exception $e){
            abort(config('my.error_log_code'),$e->getMessage());
        }
        return ['order_son'=>$order_son,"state"=>$order['state'],"list"=>$list,"results"=>$results,"outcome"=>$outcome,"fraction"=>$factor_array];
    }


    public static function order_payment($data){
        try{
            $order_son = $data['order_son'];
            $list = $data['data'];
            $arr = Db::name('order')
                ->where('order_son',$order_son)
                ->count();
            if($arr === 0){
                throw new ValidateException("未知错误");
            }
            $order = Db::name('order')
                ->where('order_son',$order_son)
                ->field("order_id,mbti_id,order_son,state,price,update_time as time")
                ->find();
            $order["time"] = date("Y-m-d H:i:s",$order["time"]);
            $price_list = Db::name("mbti_price")
                ->where("is_open","1")
                ->where("mbti_id",$order["mbti_id"])
                ->select()->toArray();
        }catch(ValidateException $e){
            throw new ValidateException ($e->getError());
        }catch(\Exception $e){
            abort(config('my.error_log_code'),$e->getMessage());
        }
        return ['order_son'=>$order_son,"order"=>$order,"price_list"=>$price_list];
    }

    public static function order_wx_pay($data,$uid){
        try{
            $order_son = $data['order_son'];
            $mp_id =$data['mp_id'];
            $type = $data['type'];//1普通浏览器2微信浏览器3微信小程序4APP
            $arr = Db::name('order')
                ->where('order_son',$order_son)
                ->count();
            if($arr === 0){
                throw new ValidateException("未知错误");
            }
            $pay_order = $order_son.time();
            $order = Db::name('order')
                ->where('order_son',$order_son)
                ->field("mbti_id,order_id,title,order_son,state,price,update_time as time")
                ->find();
//            $price = $order["price"];
            if($order["mbti_id"] == 3){
                $price_list = Db::name("mbti_price")->where("mp_id","1")->find();
            }else{
                $price_list = Db::name("mbti_price")->where("mp_id","4")->find();
            }
//            if(empty($price_list)){
//                throw new ValidateException("系统错误");
//            }
            $price = $price_list["price"];

//            $price =  '0.01';
            $order["time"] = date("Y-m-d H:i:s",$order["time"]);
            //增加记录
            Db::name('order_record')->insert([
                'o_id'=>$order['order_id'],
                'sc_order'=>$pay_order,
                'state'=>0,
                'price'=>$price,
                'type'=>1,
            ]);
            $wxpay = new wechatpay();
            $array = array(
                'body'         => '付费-'.$order['title'],
                'detail'       => '付费-'.$order['title'],
                'total_fee'    =>  $price * 100, //分
                'out_trade_no' => $pay_order,
                "notify_url"=>"https://mbtics.guoxuejianyi.com/api/Urlballback/wxnotify",
            );
            $parmen = [];
            switch ($type){//1普通浏览器2微信浏览器3微信小程序4APP
                case 1 ://h5
                    $array['trade_type'] = "MWEB";
                    $res = $wxpay ->mweb($array);
                    if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
                        $url = $res['mweb_url'];
                    }else{
                        throw new ValidateException("支付请求失败");
                    }
                    $parmen = ['order_son'=>$order_son,"url"=>$url];
                    break;
                case 2:
                    $openid = Db::name("user_wechat")->where("uid",$uid)->value("openid");
                    $array['trade_type'] = "JSAPI";
                    $res = $wxpay ->jspay($array,$data,$openid);
                    $parmen = ['order_son'=>$order_son,"res"=>$res];
                    break;
                case 3:
                    break;
                default:
                    throw new ValidateException("骚年你在搞事情!");
            }

        }catch(ValidateException $e){
            throw new ValidateException ($e->getError());
        }catch(\Exception $e){
            abort(config('my.error_log_code'),$e->getMessage());
        }
        return $parmen;
    }
    /**end**/



}

